<template>
  <el-dialog
    v-model="isVisible"
    title="轮播图设置"
    width="50%"
    :close="handleClose"
  >
    <el-upload
      ref="uploadRef"
      :action="`${BASE_URL}upload`"
      list-type="picture-card"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-error="onError"
      :on-success="handleSuccess"
      :file-list="fileList"
    >
      <el-icon
        :size="40"
      >
        <Plus />
      </el-icon>
    </el-upload>
    <template #footer>
      <div>
        <el-button
          @click="handleClose"
        >
          取消
        </el-button>
        <el-button
          type="primary"
          @click="handleConfrim"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { useVModel } from '@vueuse/core'
import config from '@/utils/config'
import notification from '@/utils/dict-notification'

const uploadRef = ref()
const props = defineProps({
  title: {
    type: String,
    default: '文件设置',
  },
  modelValue: {
    type: Boolean,
    require: true,
    default: false,
  },
  fileList: {
    type: Array,
    require: true,
    default: () => [],
  },
})
const emits = defineEmits(['update:modelValue', 'onConfirm'])
const isVisible = useVModel(props, 'modelValue', emits)

const { BASE_URL } = config

const img_id = ref([])

const handleClose = () => {
  img_id.value = []
  if (props.fileList.length === 0)
    uploadRef.value.clearFiles()

  isVisible.value = false
}

const handleConfrim = () => {
  emits('onConfirm', img_id.value)
  isVisible.value = false
}

const onError = (err) => {
  const { message } = err
  const error = JSON.parse(message)
  notification(error.code, error.message)
}

const handleRemove = (file) => {
  if (file.response)
    [file] = file.response
  if (file) {
    const idx = img_id.value.findIndex(id => file.id === id)
    if (idx !== -1)
      img_id.value.splice(idx, 1)
  }
}

const handleSuccess = (response) => {
  const [file] = response

  if (file)
    img_id.value.push(file.id)
}

watch(isVisible, (val) => {
  if (val && props.fileList.length > 0)
    img_id.value = props.fileList.map(file => file.id)
})
</script>
